import 'package:get/get.dart';
import 'package:sweetim/const/const.dart';
import 'package:sweetim/service/member_service.dart';
import 'package:web_socket_channel/io.dart';
import 'dart:convert' as convert;

typedef SocketListener = void Function(dynamic s);

class SocketService extends GetxService {
  late IOWebSocketChannel _channel;
  final _listenerList = <SocketListener>[];

  final MemberService _memberService = Get.find();

  @override
  void onInit() {
    _init();
    super.onInit();
  }

  void _init() {
    if(_memberService.token != null) {
      _channel = IOWebSocketChannel.connect(
          Uri.parse(socketHost + "?token=" + _memberService.token));
      _channel.stream.listen((message) async {
        Get.log("event: ${message}");
        for (var value in _listenerList) {
          value.call(convert.jsonDecode(message));
        }
      }, onError: (e) {
        Get.printError(info: "Error ${e}");
      }, onDone: () {
        Get.log("onDone");
        Future.delayed(Duration(seconds: 5), () {
          _init();
        });
      });
    }

  }

  void addListen(SocketListener socketListener) {
    _listenerList.add(socketListener);
  }

  void sendMsg(dynamic msg) {
    Get.log("sendMsg: $msg");
    _channel.sink.add(convert.jsonEncode(msg));
  }

  @override
  void onClose() {
    _channel.sink.close();
    super.onClose();
  }
}
